<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>聊天室</title>
    <script src="./js/jquery-1.12.3.min.js"></script>
    <script src="./js/jquery-form.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <style>
        body {
            margin-top: 5px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-3">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">当前登录用户</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group">
                        <a href="#" class="list-group-item">你好，${sessionScope.username}</a>
                        <a href="logout" class="list-group-item">退出</a>
                    </div>
                </div>
            </div>
            <div class="panel panel-primary" id="online">
                <div class="panel-heading">
                    <h3 class="panel-title">当前在线的其他用户</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group" id="users">
                    </div>
                </div>
            </div>
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title">群发系统广播</h3>
                </div>
                <div class="panel-body">
                    <input type="text" class="form-control" id="msg"/> <br/>
                    <button id="broadcast" type="button" class="btn btn-primary">发送</button>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title" id="talktitle"></h3>
                </div>
                <div class="panel-body">
                    <div class="well" id="log-container" style="height:400px;overflow-y:scroll">

                    </div>
                    <input type="text" id="myInfo" class="form-control col-md-12" maxlength="200"/> <br/>
                    <form id="fileForm" action = "sendFile" method = "POST" enctype = "multipart/form-data" target="nm_iframe">
                        <input type = "hidden" name = "MAX_FILE_SIZE" value = "100000"/>
                        <input type = "hidden" name = "uid" value = "${sessionScope.uid}"/>
                        <input type = "hidden" name = "username" value = "${sessionScope.username}"/>
                        <input type = "hidden" id = "toName" name = "toName" value = ""/>
                        <input type = "file" id="file" name = "file"/>
                    </form>
                    <button id="send" type="button" class="btn btn-primary">发送</button>
                    <iframe id="id_iframe" name="nm_iframe" style="display:none;"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
$(document).ready(function () {
    // 指定websocket路径
    var websocket;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + window.location.host + "/im/ws?uid=" +${sessionScope.uid});
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://" + window.location.host + "/im/ws" +${sessionScope.uid});
    } else {
        websocket = new SockJS("http://" + window.location.host + "/im/ws/sockjs" +${sessionScope.uid});
    }
    websocket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        if (data.to > 0) {//消息
            if (data.type == 'TEXT') {
                $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + data.fromName + "&nbsp;" + data.date + "</label><div class='text-success'>" + data.text + "</div></div><br>");
                scrollToBottom();
            } else if (data.type == 'FILE') {
                $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + data.fromName + "&nbsp;" + data.date + "</label><div class='text-success'><a href='#' onclick='downloadFile(" + data.id + ")'>" + data.text + "</a></div></div><br>");
                scrollToBottom();
            }
        } else if (data.to == 0) {//上线消息
            if (data.fromName != "${sessionScope.username}") {
                $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">' + data.fromName + '</a>');
                alert(data.text);
            }
        } else if (data.to == -1) {//广播
            if (data.fromName != "${sessionScope.username}") {
                $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + data.fromName + "&nbsp;" + data.date + "</label><div class='text-success'>" + data.text + "</div></div><br>");
            } else {
                $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;" + data.date + "</label><div class='text-info'>" + data.text + "</div></div><br>");
            }
            scrollToBottom();
        } else if (data.to == -2) {//下线消息
            if (data.fromName != "${sessionScope.username}") {
                $("#users > a").remove(":contains('" + data.fromName + "')");
                alert(data.text);
            }
        }
    };
    $.post("onlineUsers", function (data) {
        for (var i = 0; i < data.length; i++)
            $("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">' + data[i] + '</a>');
    });

    $("#broadcast").click(function () {
        $.post("broadcast",
            {
                "uid": "${sessionScope.uid}",
                "username": "${sessionScope.username}",
                "text": $("#msg").val()
            }
        );
        $("#msg").val("");
    });

    $("#send").click(function () {
        var username = $("body").data("to");
        $.post("getUid", {"username": username}, function (d) {
            var text = $("#myInfo").val();
            if (text != "") {
                var data = {};
                data["from"] = "${sessionScope.uid}";
                data["fromName"] = "${sessionScope.username}";
                data["to"] = d.uid;
                data["text"] = text;
                websocket.send(JSON.stringify(data));
                $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;" + new Date().toLocaleString() + "</label><div class='text-info'>" + text + "</div></div><br>");
                $("#myInfo").val("");
                scrollToBottom();
            }
        });

        var file = document.getElementById("file").value;
        if (file != "") {
            $("#toName").val(username);
            /*$("#fileForm").submit();*/
            $("#fileForm").ajaxSubmit(function(data){
                $("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;" + data.date + "</label><div class='text-info'><a href='#' onclick='downloadFile(" + data.id + ")'>" + data.text + "</a></div></div><br>");
            });
            document.getElementById("file").value = "";
            scrollToBottom();
        }
        scrollToBottom();
    });

});

function downloadFile(id, name) {
    window.open("http://" + window.location.host + "/im/download?id=" + id);
}

function talk(a) {
    $("#talktitle").text("与" + a.innerHTML + "的聊天");
    $("body").data("to", a.innerHTML);
    $("#toName").val(a.innerHTML);

    refresh();
    scrollToBottom();
}

function refresh() {
    $.post("history",
        {
            "from": "${sessionScope.uid}",
            "toName": $("body").data("to")
        },
        function (d) {
            var len = d.length;
            if (len > 0) {
                $("#log-container").empty();
                for (var j = 0; j < len; j++) {
                    var data = d[j];
                    if (data.fromName != "${sessionScope.username}") {
                        if (data.type == 'TEXT') {
                            $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + data.fromName + "&nbsp;" + data.date + "</label><div class='text-success'>" + data.text + "</div></div><br>");
                        } else if (data.type == 'FILE') {
                            $("#log-container").append("<div class='bg-info'><label class='text-danger'>" + data.fromName + "&nbsp;" + data.date + "</label><div class='text-success'><a href='#' onclick='downloadFile(" + data.id + ")'>" + data.text + "</a></div></div><br>");
                        }
                    } else {
                        if (data.type == 'TEXT') {
                            $("#log-container").append("<div class='bg-info'><label class='text-info'>我&nbsp;" + data.date + "</label><div class='text-info'>" + data.text + "</div></div><br>");
                        } else if (data.type == 'FILE') {
                            $("#log-container").append("<div class='bg-info'><label class='text-info'>我&nbsp;" + data.date + "</label><div class='text-info'><a href='#' onclick='downloadFile(" + data.id + ")'>" + data.text + "</a></div></div><br>");
                        }
                    }
                }
                scrollToBottom();
            }
        }
    );
}

function scrollToBottom() {
    var div = document.getElementById('log-container');
    div.scrollTop = div.scrollHeight;
}



</script>

</body>
</html>
